package com.ruoyi.application.util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 阿里云账号管理器
 * 用于管理多个阿里云账号，当请求次数达到限制时自动切换账号
 */
public class AliyunAccountManager {
    
    /**
     * 阿里云账号信息类
     */
    public static class AliyunAccount {
        private String accessKeyId;
        private String accessKeySecret;
        private AtomicInteger requestCount;
        private final int maxRequests;
        
        public AliyunAccount(String accessKeyId, String accessKeySecret, int maxRequests) {
            this.accessKeyId = accessKeyId;
            this.accessKeySecret = accessKeySecret;
            this.requestCount = new AtomicInteger(0);
            this.maxRequests = maxRequests;
        }
        
        public String getAccessKeyId() {
            return accessKeyId;
        }
        
        public String getAccessKeySecret() {
            return accessKeySecret;
        }
        
        public int getRequestCount() {
            return requestCount.get();
        }
        
        public int getMaxRequests() {
            return maxRequests;
        }
        
        public boolean isAvailable() {
            return requestCount.get() < maxRequests;
        }
        
        public void incrementRequestCount() {
            requestCount.incrementAndGet();
        }
        
        public void resetRequestCount() {
            requestCount.set(0);
        }
        
        @Override
        public String toString() {
            return String.format("Account[%s, requests: %d/%d]", 
                accessKeyId.substring(0, 8) + "***", requestCount.get(), maxRequests);
        }
    }
    
    private static final AliyunAccountManager INSTANCE = new AliyunAccountManager();
    private final List<AliyunAccount> accounts;
    private final AtomicInteger currentAccountIndex;
    private final ReentrantLock lock;
    
    private AliyunAccountManager() {
        this.accounts = new ArrayList<>();
        this.currentAccountIndex = new AtomicInteger(0);
        this.lock = new ReentrantLock();
        initializeAccounts();
    }
    
    public static AliyunAccountManager getInstance() {
        return INSTANCE;
    }
    
    /**
     * 初始化账号列表
     */
    private void initializeAccounts() {
        // 添加您提供的4个账号，每个账号限制190次请求
        accounts.add(new AliyunAccount("LTAI5tJ8WW9h4cD7i9BwAT58", "c2QSLzOD14iMgRfS8k3tWPEWCQyHjG", 190));
        accounts.add(new AliyunAccount("LTAl5t8ez2Y1PPai6wzc5nE3", "s75y2tq0MgOskAc4cU6HI05gED3rLD", 190));
        accounts.add(new AliyunAccount("LTAI5tEiXmHVefTnzKskw5LZ", "GTpJ0F7raLZB7g4VMeXOFcP7EZ5L7b", 190));
        accounts.add(new AliyunAccount("LTAI5tMEywvCWGGrYzbccc32", "aSYgrDEBwj3piBdHBEjDNxznfrXz74", 190));
    }
    
    /**
     * 获取当前可用的账号
     * 如果当前账号已达到请求限制，自动切换到下一个可用账号
     */
    public AliyunAccount getCurrentAccount() {
        lock.lock();
        try {
            // 检查当前账号是否可用
            AliyunAccount currentAccount = accounts.get(currentAccountIndex.get());
            if (currentAccount.isAvailable()) {
                return currentAccount;
            }
            
            // 当前账号不可用，寻找下一个可用账号
            int startIndex = currentAccountIndex.get();
            int nextIndex = (startIndex + 1) % accounts.size();
            
            // 循环查找可用账号
            while (nextIndex != startIndex) {
                AliyunAccount nextAccount = accounts.get(nextIndex);
                if (nextAccount.isAvailable()) {
                    currentAccountIndex.set(nextIndex);
                    System.out.println("切换到账号: " + nextAccount.toString());
                    return nextAccount;
                }
                nextIndex = (nextIndex + 1) % accounts.size();
            }
            
            // 所有账号都已达到限制，返回第一个账号并重置计数器
            System.out.println("所有账号都已达到请求限制，重置所有账号计数器");
            resetAllAccounts();
            currentAccountIndex.set(0);
            return accounts.get(0);
            
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 使用账号（增加请求计数）
     */
    public void useAccount() {
        lock.lock();
        try {
            AliyunAccount currentAccount = accounts.get(currentAccountIndex.get());
            currentAccount.incrementRequestCount();
            System.out.println("使用账号: " + currentAccount.toString());
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 重置所有账号的请求计数
     */
    public void resetAllAccounts() {
        lock.lock();
        try {
            for (AliyunAccount account : accounts) {
                account.resetRequestCount();
            }
            System.out.println("已重置所有账号的请求计数");
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 获取账号状态信息
     */
    public String getAccountStatus() {
        lock.lock();
        try {
            StringBuilder status = new StringBuilder();
            status.append("账号使用状态:\n");
            for (int i = 0; i < accounts.size(); i++) {
                AliyunAccount account = accounts.get(i);
                String marker = (i == currentAccountIndex.get()) ? " [当前]" : "";
                status.append(String.format("账号%d: %s%s\n", i + 1, account.toString(), marker));
            }
            return status.toString();
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 添加新账号
     */
    public void addAccount(String accessKeyId, String accessKeySecret, int maxRequests) {
        lock.lock();
        try {
            accounts.add(new AliyunAccount(accessKeyId, accessKeySecret, maxRequests));
            System.out.println("添加新账号: " + accessKeyId.substring(0, 8) + "***");
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 获取总账号数量
     */
    public int getAccountCount() {
        return accounts.size();
    }
    
    /**
     * 获取当前账号索引
     */
    public int getCurrentAccountIndex() {
        return currentAccountIndex.get();
    }
}
